"use client"
import React, {useEffect, useState} from "react";
import {
    Button,
    Col,
    Form,
    Input,
    message,
    Modal,
    Row,
    Select,
    Space,
    Switch,
    Table,
    TableProps,
    Tooltip,
    Tree
} from 'antd';

import ThreeComponent from "./component/ThreeComponent"
import {changeUserStatus, delUser, listUser} from "@/clientApi/system/user";
import {DatePicker} from 'antd';
import {DeleteOutlined, PlusOutlined} from "@ant-design/icons";
import EditUser from "./component/EditUser";
import ResetPassWordUser from "./component/ResetPassWordUser";
import AuthRoleView from "./component/AuthRoleView";
import useResponsiveLayout from "@/utils/useResponsiveLayout";
import { globalMessage } from "@/utils/message";
import RenderIconsCustom from "@/components/CustomIconSelector/conponents";
import { useConfirmModal } from "@/utils/ConfirmModal";

const UserView: React.FC = () => {
        const { confirm } = useConfirmModal();
    const initialQueryParams = {
        pageNum: 1,
        pageSize: 10,
        deptName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,

    };

    interface DataType {
    }
// 用户管理
    const [form] = Form.useForm();
    const [record, setRecord] = useState<Record<string, any>>({});
    const [forceUpdateKey, setForceUpdateKey] = useState(0); // 用于强制更新组件的 key
    const [dataList, setDataList] = useState<DataType[]>([]);
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '用户编号',
            dataIndex: 'userId',
            key: 'userId',
            width: '200',
            align: 'center',
        },
        {
            title: '用户名称',
            dataIndex: 'userName',
            key: 'userName',
            align: 'center',
        },
        {
            title: '用户昵称',
            dataIndex: 'nickName',
            key: 'nickName',
            align: 'center',
        }, {
            title: '部门',
            dataIndex: 'deptName',
            key: 'deptName',
            align: 'center',
        }, {
            title: '手机号码',
            dataIndex: 'phonenumber',
            key: 'phonenumber',
            align: 'center',
        }, {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            render: (_, record:any) => (
                <Space size="middle">
                    {record?.userId !== 1 &&
                        <Switch key={forceUpdateKey + record.userId} defaultValue={record.status === "0"}
                                onChange={(checked, event) => onChangeStatus(checked, event, record)}
                                checkedChildren="开启"
                                unCheckedChildren="关闭"/>
                    }
                </Space>)
        }, {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center',
        }, {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            align: 'center',
            render: (_, record:any) => (
                <Space size="middle">
                    {record?.userId !== 1 && (
                        <Tooltip title="修改">
                            <Button
                                type="link"
                                size="small"
                                icon={<RenderIconsCustom icon="edit"/>}
                                onClick={() => EditClick(record)}/>
                        </Tooltip>

                    )}
                    {record?.userId !== 1 && (
                        <Tooltip title="删除">
                            <Button
                                type="link"
                                size="small"
                                icon={<DeleteOutlined/>}
                                onClick={() => handleDelete(record)}/>
                        </Tooltip>
                    )}
                    {record?.userId !== 1 && (
                        <Tooltip title="重置密码">
                            <Button
                                type="link"
                                size="small"
                                icon={<RenderIconsCustom icon="password"/>}
                                onClick={() => {
                                    setRecord(record);setResetOpen(true);
                                }}/>
                        </Tooltip>

                    )}
                    {record?.userId !== 1 && (
                        <Tooltip title="分配角色">
                            <Button
                                type="link"
                                size="small" icon={<PlusOutlined/>}
                                onClick={() => {setAuthOpen(true);setRecord(record);
                                }}/>
                        </Tooltip>
                    )}

                </Space>
            ),
        },
    ];
    const [queryParams, setQueryParams] = useState(initialQueryParams);
    const [total, setTotal] = useState(0);
    const [title, setTitle] = useState('');
    const [open, setOpen] = useState<boolean>(false);
    const [resetOpen, setResetOpen] = useState<boolean>(false);
    const [authOpen, setAuthOpen] = useState<boolean>(false);
    const [userId, setUserId] = useState<string|undefined>(undefined);
    useEffect(() => {
        getList();
    }, [queryParams]);  // 监听 queryParams 变化，调用 getList

    /** 查询用户列表 */
    const getList=()=> {
        listUser(queryParams).then((res:any) => {
            setDataList(res.rows.map((item: any) => ({
                ...item,
                deptName: item.dept?.deptName,
                key: item.userId // 使用 userId 作为唯一的 key
            })))
            setTotal(res.total); // 更新 total，用于分页
        });
    }

    // 查询列表
    const handleSearch=()=> {
        form.validateFields().then(values => {
            console.log(values, 'values')
            setQueryParams(prevQueryParams => ({
                ...queryParams,
                deptName: values.deptName,
                status: values.status,
                phonenumber: values.phonenumber,
                 "params[beginTime]": values.dateRange ? values.dateRange[0].format("YYYY-MM-DD") : null,
                "params[endTime]": values.dateRange ? values.dateRange[1].format("YYYY-MM-DD") : null,
            }));
        });
    }

    // 重置查询
    const resetSearch = () => {
        form.resetFields();
        setQueryParams(initialQueryParams); // 重置为初始状态
    }

    // 分页变化
    const handleTableChange = (page: number, pageSize: number) => {
        setQueryParams({
            ...queryParams,
            pageNum: page,
            pageSize: pageSize,
        });
    };
    // 修改按钮
    const EditClick = (e: any) => {
        setUserId(e.userId)
        setTitle("修改用户")
        setOpen(true)
    }
    // 删除按钮
    const handleDelete = (e: any) => {
        const userIds = e.userId;
        confirm({
            title: '系统提示',
            content: (`是否确认删除用户编号为"${userIds}"的数据项？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                delUser(userIds).then((res: any) => {
                    if (res?.code === 200) {
                         globalMessage().info("删除成功")
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作

            },
        });

    }
    const onChangeStatus = (checked: boolean, event: any, value: any) => {
        const text = value.status === "0" ? "启用" : "停用";
        confirm({
            title: '系统提示',
            content: (`确认要"${text}"+"${value.userName}"用户吗？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                changeUserStatus(value.userId, checked === false ? "1" : "0").then((res:any) => {
                    if (res?.code === 200) {
                         globalMessage().info("修改成功")
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作
                setForceUpdateKey(prevKey => prevKey + 1); // 更新 key 以强制重新渲染组件
            },
        });
        // console.log(checked,event,value,value.status == "0")
    }

// 点击查询对应的部门数据
    const handleNodeTree=(e: any)=> {
        setQueryParams(prevQueryParams => ({
            ...queryParams,
            deptId: e.node.id,

        }));
    }

    return (
        <div className='home'>
            <Row gutter={20} style={{paddingTop: "20px"}}>
                <Col span={4}>
                    <ThreeComponent handleNodeTree={(e: any) => handleNodeTree(e)}/>
                </Col>
                <Col span={20}>
                    <div><Form
                        form={form}
                        name="customized_form_controls"
                        style={{marginTop: 10, marginLeft: 10, marginBottom: 10}}
                       layout={useResponsiveLayout("inline")}>
                        <Form.Item
                            name="deptName"
                            label="用户名称">
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            name="status"
                            label="状态">
                            <Select
                                style={{
                                    width: 120,
                                }}

                                allowClear
                                options={[
                                    {
                                        value: 0,
                                        label: '正常',
                                    }, {
                                        value: 1,
                                        label: '停用',
                                    },
                                ]}
                            />
                        </Form.Item>
                        <Form.Item
                            name="phonenumber"
                            label="手机号码">
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            name="dateRange"
                            label="日期">
                            <DatePicker.RangePicker format="YYYY-MM-DD"/>
                        </Form.Item>

                        <Form.Item>
                            <Button type="primary" htmlType="submit" onClick={handleSearch} style={{
                                marginRight: 20,
                            }}>
                                查询
                            </Button>
                            <Button type="primary" htmlType="reset" onClick={resetSearch}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form></div>
                    <div><Button type="primary" ghost onClick={() => {
                        setOpen(true);
                        setUserId(undefined);
                        setTitle("新增用户")
                    }} style={{margin: 10}}>
                        新增
                    </Button></div>
                    <Table<DataType> scroll={{x:'max-content'}} columns={columns} dataSource={dataList} pagination={{
                        current: queryParams.pageNum,
                        pageSize: queryParams.pageSize,
                        total: total,
                        showSizeChanger: true, // 显示分页尺寸切换器
                        pageSizeOptions: ['10', '20', '50'], // 分页尺寸选项
                        onChange:handleTableChange
                    }} />
                </Col>
            </Row>
            {open&&<EditUser title={title} open={open} userId={userId} OnCanCle={() => {
                setOpen(false);
                getList();
            }}/>}
            {resetOpen&&<ResetPassWordUser open={resetOpen} title={"修改密码"} record={record} OnCanCle={() => {
                setResetOpen(false);
                getList();
            }}/>}
            {authOpen&&<AuthRoleView open={authOpen} title={"分配用户"} record={record} OnCanCle={() => {
                setAuthOpen(false);
                getList();
            }}/>}
        </div>
    )
};
export default UserView;
